package top.soft.windows;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import top.soft.util.CommonData;
import top.soft.util.NetWork;
import top.soft.util.Request;
import top.soft.util.Response;

/**
 * @ClassName: ShowView
 * @Author: Amosen
 * @Since: 2021/4/21
 */

// 这个类用于展示选项卡，同时给予搜索和展示的功能
public class ShowView extends JPanel {

	private JTextField searchBar;
	private JButton confirmBtn, deleteBtn, refreshBtn;
	private JTable dataTable;
	private String[][] cache;
	private String selectedAccount;

	public ShowView() {
		init();
	}

	private void init() {
		// 从后端接收用户数据，数据以二维数组形式保存在CommonData.userData下;
		getData();

		setLayout(new BorderLayout());

		// 准备搜索框和搜索按钮
		searchBar = new JTextField(15);
		searchBar.addKeyListener(new FindKeyListener());
		confirmBtn = new JButton(CommonData.SEARCH_BTN);
		confirmBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				doFind();
			}
		});

		deleteBtn = new JButton(CommonData.DELETE_BTN);
		deleteBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				doDelete();
			}
		});

		refreshBtn = new JButton(CommonData.REFRESH_BTN);
		refreshBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getData();
				setTable(CommonData.userData);
			}
		});

		// 准备表格
		setTable(CommonData.userData);
		JScrollPane scrollPane = new JScrollPane(dataTable);
		dataTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		JPanel panelNorth = new JPanel();
		panelNorth.setLayout(new FlowLayout());

		// 将组件添加到面板中
		panelNorth.add(searchBar);
		panelNorth.add(confirmBtn);
		panelNorth.add(deleteBtn);
		panelNorth.add(refreshBtn);
		add(panelNorth, BorderLayout.NORTH);
		add(scrollPane, BorderLayout.CENTER);
	}

	private class FindKeyListener extends KeyAdapter {
		@Override
		public void keyTyped(KeyEvent e) {
			super.keyTyped(e);
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				doFind();
			}
		}
	}

	private boolean check() {
		String condition = searchBar.getText();
		if (condition == null) {
			searchBar.requestFocus();
			setTable(CommonData.userData);
			return false;
		} else {
			if ("".equals(condition) || condition.trim().length() == 0) {
				searchBar.setText("");
				searchBar.requestFocus();
				setTable(CommonData.userData);
				return false;
			} else {
				return true;
			}
		}
	}

	public void doDelete() {
		int selectedRow = dataTable.getSelectedRow();
		if (selectedRow == -1) {
			return;
		} else {
			try {
				selectedAccount = (String) dataTable.getModel().getValueAt(selectedRow, 0);
				String loginAccount = CommonData.getUser().getAccount();
				Request request = new Request(CommonData.DELETE_USER_PATH, Request.GET);
				request.addData("loginAccount", loginAccount).addData("account", selectedAccount);
				Response response = NetWork.service(request);
				if (response == null) {
					JOptionPane.showMessageDialog(null, "网络连接失败！");
				} else {
					Integer code = response.getCode();
					if (code == 504) {
						JOptionPane.showMessageDialog(null, "您没有权限！");
					} else if (code == 503) {
						JOptionPane.showMessageDialog(null, "该账户不存在！");
					} else {
						// 删除成功
						DefaultTableModel tableModel = (DefaultTableModel) dataTable.getModel();
						tableModel.removeRow(selectedRow);
						getData();
						setTable(CommonData.userData);
						JOptionPane.showMessageDialog(null, "删除成功！");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	// 查找事件
	private void doFind() {
		if (!check()) {
			return;
		} else {
			// 获取搜索条件
			String condition = searchBar.getText();
			// 封装为Request对象
			Map<String, String> param = new HashMap<>();
			param.put("param", condition);
			Request request = new Request(CommonData.SEARCH_PATH, Request.GET, param);
			// 发起请求
			Response resp = NetWork.service(request);
			if (resp == null) {
				return;
			} else {
				if (resp.getCode() != 200) {
					JOptionPane.showMessageDialog(null, "获取搜索结果失败！");
					return;
				} else {
					try {
						List<LinkedHashMap<String, Object>> userMaps = (List<LinkedHashMap<String, Object>>) resp
								.getData().get("user");
						String[][] result = new String[userMaps.size()][CommonData.TABLE_COLUMNS_NUM];
						int i = 0;
						for (LinkedHashMap<String, Object> userMap : userMaps) {
							String account = (String) userMap.get("account");
							Integer auth = (Integer) userMap.get("auth");
							String strAuth = String.valueOf(auth);
							String[] col = { account, strAuth };
							result[i] = col;
							i++;
						}
						cache = result;
						setTable(cache);
					} catch (Exception e) {
						JOptionPane.showMessageDialog(null, "程序发生异常！错误代码：" + CommonData.CLASS_CAST_EXCEPTION_CODE);
					}
				}
			}

		}

	}

	private void setTable(String[][] result) {
		if (dataTable == null) {
			dataTable = new JTable();
		}
		TableModel tableModel = new DefaultTableModel(result, CommonData.TABLE_HEADER);
		dataTable.setModel(tableModel);
		dataTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	}

	private void getData() {
		// 封装Request对象
		Request request = new Request(CommonData.GET_ALL_PATH, Request.GET);
		Response response = NetWork.service(request);
		if (response == null) {
			JOptionPane.showMessageDialog(null, "网络连接失败，数据初始化失败");
		} else {
			if (response.getCode() != 200) {
				JOptionPane.showMessageDialog(null, "请求失败，请检查后重试");
			} else {
				try {
					List<LinkedHashMap<String, Object>> userMaps = (List<LinkedHashMap<String, Object>>) response
							.getData().get("user");
					String[][] result = new String[userMaps.size()][CommonData.TABLE_COLUMNS_NUM];
					int i = 0;
					for (LinkedHashMap<String, Object> userMap : userMaps) {
						String account = (String) userMap.get("account");
						Integer auth = (Integer) userMap.get("auth");
						String strAuth = String.valueOf(auth);
						String[] col = { account, strAuth };
						result[i] = col;
						i++;
					}
					// 将封装结果添加到公共数据中
					CommonData.userData = result;
				} catch (Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "程序发生异常！错误代码：" + CommonData.CLASS_CAST_EXCEPTION_CODE);
				}

			}
		}
	}

}
